﻿using System;
using System.Collections.Generic;
using System.Linq;
using NetSurveillance.WebApp.DataServices.Models;
using ServiceStack.OrmLite;

namespace NetSurveillance.WebApp.DataServices.Implementations
{
    public class SetupWizardService : BaseService<SetupWizard>
    {
        public SetupWizardService(string connStr, IOrmLiteDialectProvider provider = null)
            : base(connStr, provider)
        {
        }

        public ServiceResult Save(SetupWizard setupWizard, long caseId, Task task, IEnumerable<Keyword> keywords)
        {
            using (var db = DbFactory.OpenDbConnection())
            {
                using (var trans = db.OpenTransaction())
                {
                    try
                    {
                        db.Insert(task);
                        long taskId = db.GetLastInsertId();
                        task.Id = setupWizard.TaskId = taskId;
                        db.Insert(setupWizard);
                        setupWizard.Id = db.GetLastInsertId();
                        if (keywords != null)
                        {
                            foreach (var keyword in keywords.Where(keyword => keyword != null))
                            {
                                keyword.TaskId = taskId;
                                db.Insert(keyword);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        //todo:log the save exception
                        trans.Rollback();
                        return new ServiceResult {ExecutedSuccess = false, Message = ex.Message};
                    }
                    trans.Commit();
                }
            }
            return ServiceResult.SuccessResult;
        }
    }
}